/*
 * Java Basics Practical Tasks module1
 * 2. Array neighbouring numbers
 */

package module1;

import java.util.*;
/**
 *
 * @author Antonina Cherednichenko
 */
public class ArrayMembers {
    /**
     *
     * @return - return index of first element with shortest distance
     */
    private static int findSmallestDistance(int[] array) {
        int min = Integer.MAX_VALUE;
        int result = -1;
        for (int i = 0; i < array.length - 1; i++) {
            int distance = Math.abs(array[i] - array[i + 1]);
            if (distance < min) {
                min = distance;
                result = i;
            }
        }
        return result;
    }

    /**
     * Function for getting valid input: number of elements in array (positive number) and array
     * If input is invalid, exception is thrown, handled inside testFunction
     * @ return - array of members
     */
    private static int[] getValidInput(Scanner in) throws InputMismatchException {
        System.out.println("Enter number of elements in your sequence");
        int num  = in.nextInt(); // can throw exception, caught below
        if (num <= 0) throw new InputMismatchException();
        int[] result = new int[num];
        for (int i = 0; i < num; i++) {
           System.out.println("Enter next number:");
           int val = in.nextInt(); //throwing exception again
           result[i] = val;
        }
        return result;
    }

    private static void printResults(int[] array, int index) {
        System.out.printf("for array %s result is %d\n", Arrays.toString(array), index);
    }

    /**
     * Function for linking all logic together, is called from main Module1 class
     */
    public static void testFunction() {
        Scanner in = new Scanner (System.in);
        System.out.println("Testing function for smallest distance");
        try {
            int[] inputArray = getValidInput(in);
            int resultIndex = findSmallestDistance(inputArray);
            printResults(inputArray, resultIndex);
        } catch (InputMismatchException exc) {
            System.out.println("Wrong input, only numbers are expected");
            System.out.println("Or if you are entering array size, it have to be positive number, greater than 0");
        } 
    }
}
